<template>
  <div class="min-h-screen bg-gray-50 flex flex-col items-center justify-center p-4">
    <h1 class="text-2xl font-bold text-gray-800 mb-6">双Token无感刷新测试</h1>
    
    <div class="bg-white rounded-lg shadow-md p-6 w-full max-w-md">
      <div class="mb-4">
        <h2 class="text-lg font-semibold text-gray-700 mb-2">当前状态</h2>
        <p class="text-gray-600" v-if="accessToken">访问Token: {{ getToken.accessToken.substring(0, 10) }}...</p>
        <p class="text-gray-600" v-if="refreshToken">刷新Token: {{ getToken.refreshToken.substring(0, 10) }}...</p>
        <p class="text-red-500" v-else>未登录</p>
      </div>
      
      <div class="flex space-x-4 mb-6">
        <button @click="login" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors">
          登录
        </button>
        <button @click="logout" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600 transition-colors">
          登出
        </button>
      </div>
      
      <div class="mb-6">
        <button @click="testApi" class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 transition-colors w-full">
          测试API请求
        </button>
      </div>
      
      <div class="mb-4">
        <h2 class="text-lg font-semibold text-gray-700 mb-2">请求结果</h2>
        <pre class="bg-gray-100 p-3 rounded overflow-auto max-h-40 text-sm" v-if="apiResult">{{ apiResult }}</pre>
        <p class="text-gray-500 italic" v-else>点击测试按钮查看结果</p>
      </div>
      
      <div class="mb-4">
        <h2 class="text-lg font-semibold text-gray-700 mb-2">日志</h2>
        <div class="bg-gray-100 p-3 rounded overflow-auto max-h-40 text-sm space-y-1">
          <p v-for="log in logs" :key="log.id" :class="log.type === 'error' ? 'text-red-500' : 'text-gray-600'">
            {{ log.time }}: {{ log.message }}
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useUserStore } from '~/stores/user'
import { useCookie } from 'nuxt/app'

const userStore = useUserStore()
const accessToken = useCookie('accessToken')
const refreshToken = useCookie('refreshToken')

const getToken = computed(() => {
  return {
    accessToken: accessToken.value || '',
    refreshToken: refreshToken.value || ''
  }
})
const apiResult = ref<string | null>(null)
const logs = ref<Array<{ id: number, time: string, message: string, type: 'info' | 'error' }>>([])
let logId = 0

// 添加日志
const addLog = (message: string, type: 'info' | 'error' = 'info') => {
  const time = new Date().toLocaleTimeString()
  logs.value.push({ id: logId++, time, message, type })
  // 限制日志数量
  if (logs.value.length > 20) {
    logs.value.shift()
  }
}

// 登录
const login = async () => {
  try {
    addLog('正在登录...')
    const loginResponse = await useApi<{
      code: number;
      message: string;
      data: {
        accessToken: string;
        refreshToken: string;
        user: {
          nickname: string;
          avatar: string;
          id: number;
        }
      }
    }>('/api/login', {
      method: 'POST',
      body: {
        username: 'test', // 替换为实际测试用户名
        password: 'test'  // 替换为实际测试密码
      }
    })
    
    if (loginResponse.code === 200) {
      userStore.setUser(loginResponse.data.user)
      addLog('登录成功')
    } else {
      addLog('登录失败: ' + loginResponse.message, 'error')
    }
  } catch (error: any) {
    addLog('登录出错: ' + (error.message || '未知错误'), 'error')
  }
}

// 登出
const logout = () => {
  userStore.clearTokens()
  userStore.setUser({ nickname: '', avatar: '', id: 0 })
  apiResult.value = null
  addLog('已登出')
}

// 测试API请求
const testApi = async () => {
  try {
    addLog('发送API请求...')
    const response = await useApi<{
      code: number;
      message: string;
      data: any
    }>('/api/music-list', {
      method: 'GET'
    })
    
    apiResult.value = JSON.stringify(response, null, 2)
    addLog('API请求成功')
  } catch (error: any) {
    apiResult.value = JSON.stringify(error, null, 2)
    addLog('API请求失败: ' + (error.message || '未知错误'), 'error')
  }
}

// 页面加载时检查登录状态
onMounted(() => {
  if (accessToken.value) {
    addLog('已登录')
  } else {
    addLog('未登录')
  }
})

definePageMeta({
  middleware: ['auth']
})
</script>

<style scoped>
/* 可以添加一些简单的样式 */
</style>